package ysf.com.simplediffculty;

/**
 * @author ysf
 * @date 2021/6/25 22:05
 * 在一个String类型的数组中找到末尾字符相同字符并截取
 *
 */
public class FourteenthDemo {


    public static void main(String[] args) {

        String[] str = new String[]{"flow","asow","fligow"};
        String s = longestCommonPrefix(str);
        System.out.println(s);

    }

    public static boolean isSameAtIndex(String[] str,int index){
        int i = 0;
        while (i<str.length - 1){
            if (str[i].charAt(str[i].length()-index-1) == str[i+1].charAt(str[i+1].length()-index-1)){
                i++;
            }else {
                return false;
            }
        }
        return true;
    }

    public static String longestCommonPrefix(String[] strs){

        if (strs.length == 0){
            return "";
        }
        // 得到最短的字符串的长度
        int minLength = Integer.MAX_VALUE;
        for (int i = 0; i < strs.length; i++) {
            if (strs[i].length()<minLength){
                minLength = strs[i].length();
            }
        }
        int j = 0;
        // 遍历所有
        for (;j<minLength;j++){
            // 如果当前列字符不完全相同，则结束循环
            if(!isSameAtIndex(strs,j)){

                break;
            }
        }
        return strs[0].substring(j,strs[0].length());
    }




}
